﻿using System;
using System.Linq;

namespace oueb.core
{
    using Ceen;
    using System.Threading.Tasks;

    public class CorsPolicy : IHttpModule
    {
        public CorsPolicy(bool credentials, string headers, string methods, string origin)
        {
            this.Credentials = credentials;
            this.Headers = headers;
            this.Methods = methods;
            this.Origin = origin;
        }

        public bool Credentials { get; }
        public string Headers { get; }
        public string Methods { get; }
        public string Origin { get; }

        public Task<bool> HandleAsync(IHttpContext context)
        {
            if (!string.IsNullOrEmpty(this.Origin))
            {
                if (context.Request.Headers.TryGetValue("origin", out var origin))
                {
                    if (!this.Origin.Split(",").Contains(origin))
                        origin = this.Origin;
                }
                else
                    origin = this.Origin;

                context.Response.Headers.Add("Access-Control-Allow-Origin", origin);

            }

            if (this.Credentials)
                context.Response.Headers.Add("Access-Control-Allow-Credentials", this.Credentials.ToString().ToLower());

            if (!string.IsNullOrEmpty(this.Headers))
                context.Response.Headers.Add("Access-Control-Allow-Headers", this.Headers);

            if (!string.IsNullOrEmpty(this.Methods))
                context.Response.Headers.Add("Access-Control-Allow-Methods", this.Methods);
            return Task.FromResult(false);
        }
    }
}
